package com.kecheng.util;

import com.kecheng.action.BaseAction;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
	public static void mkDir(String path) {
		System.out.println("目录:"+path);
	        File fd = null;  
	        try {  
	            fd = new File(path);  
	            if (!fd.exists()) {  
	                fd.mkdirs();  
	            }  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            fd = null;  
	        }  
	    }
	
	/**
	 * 传入File,保存后,其实,这个东西可以在图片上传的过程中就存入,可以
	 * 节省一半的IO消耗返回路径
	 * @param file
	 * @return
	 */
	public static String pictureUtil(File file,String fileFileName,String root) {
		InputStream is = null;
		OutputStream os = null;
		try {
			fileFileName=System.currentTimeMillis()+fileFileName;
			FileUtil.mkDir(root);
			is = new FileInputStream(file);
			os = new FileOutputStream(new File(root, fileFileName));
			byte[] buffer = new byte[2048];
			int length = 0;
			while (-1 != (length = is.read(buffer, 0, buffer.length))) {
				os.write(buffer);
			}
			return "upload/" + fileFileName;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e1) {

		} finally {
			try {
				if(os!=null)os.close();
				if(is!=null)is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "";
	}
}
